package com.demo.youxuanmall.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/admin/products")
public class AdminProductController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public String list(Model model,
                      @RequestParam(defaultValue = "1") Integer pageNum,
                      @RequestParam(defaultValue = "10") Integer pageSize,
                      @RequestParam(required = false) String keyword) {
        // 分页查询
        Page<Product> page = new Page<>(pageNum, pageSize);
        Page<Product> productPage = productService.getAdminProductPage(page, keyword);
        
        model.addAttribute("page", productPage);
        model.addAttribute("keyword", keyword);
        return "admin/product/list";
    }

    @GetMapping("/add")
    public String add() {
        return "admin/product/add";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        Product product = productService.getById(id);
        model.addAttribute("product", product);
        return "admin/product/edit";
    }

    @PostMapping("/save")
    @ResponseBody
    public Result save(@RequestParam(value = "id", required = false) Long id,
                      @RequestParam("name") String name,
                      @RequestParam("subtitle") String subtitle,
                      @RequestParam("categoryId") Long categoryId,
                      @RequestParam("price") BigDecimal price,
                      @RequestParam("stock") Integer stock,
                      @RequestParam("status") Integer status,
                      @RequestParam("detail") String detail,
                      @RequestParam(value = "mainImage", required = false) MultipartFile mainImage,
                      @RequestParam(value = "subImages", required = false) MultipartFile[] subImages,
                      HttpSession session) {
        // 检查是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }

        try {
            // 创建商品对象
            Product product = new Product();
            if (id != null) {
                product.setId(id);
                // 如果是编辑，先获取原有商品信息
                Product existingProduct = productService.getById(id);
                if (existingProduct != null) {
                    product.setMainImage(existingProduct.getMainImage());
                    product.setSubImages(existingProduct.getSubImages());
                }
            }
            
            product.setName(name);
            product.setSubtitle(subtitle);
            product.setCategoryId(categoryId);
            product.setPrice(price);
            product.setStock(stock);
            product.setStatus(status);
            product.setDetail(detail);

            // 处理主图
            if (mainImage != null && !mainImage.isEmpty()) {
                String mainImageUrl = uploadImage(mainImage);
                product.setMainImage(mainImageUrl);
            }

            // 处理子图
            if (subImages != null && subImages.length > 0) {
                List<String> subImageUrls = new ArrayList<>();
                for (MultipartFile subImage : subImages) {
                    if (!subImage.isEmpty()) {
                        String subImageUrl = uploadImage(subImage);
                        subImageUrls.add(subImageUrl);
                    }
                }
                if (!subImageUrls.isEmpty()) {
                    product.setSubImages(String.join(",", subImageUrls));
                }
            }

            productService.saveOrUpdate(product);
            return Result.success();
        } catch (Exception e) {
            log.error("保存商品失败", e);
            return Result.error("保存失败：" + e.getMessage());
        }
    }

    private String uploadImage(MultipartFile file) throws IOException {
        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        
        // 生成新的文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        
        // 获取项目根目录
        String projectPath = System.getProperty("user.dir");
        
        // 设置上传目录
        String uploadDir = projectPath + "/upload/images/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 保存文件
        File destFile = new File(dir, fileName);
        file.transferTo(destFile);
        
        // 返回文件访问路径
        return "/upload/images/" + fileName;
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result delete(@PathVariable Long id, HttpSession session) {
        // 检查是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }

        try {
            productService.removeById(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除商品失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    @PostMapping("/status/{id}")
    @ResponseBody
    public Result updateStatus(@PathVariable Long id, @RequestParam Integer status, HttpSession session) {
        // 检查是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }

        try {
            Product product = new Product();
            product.setId(id);
            product.setStatus(status);
            productService.updateById(product);
            return Result.success();
        } catch (Exception e) {
            log.error("更新商品状态失败", e);
            return Result.error("更新状态失败：" + e.getMessage());
        }
    }
} 